package com.shengwei.truck.driver.view.ui.mine.userinfo;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.JsonPostFileData;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.ActivityPersonalInfoBinding;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.selfview.SelectPicPopupWindow;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.vm.PersonalInfoViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import io.reactivex.functions.Consumer;

/**
 * 用户个人信息
 */
public class PersonalInfoActivity extends BaseActivity<PersonalInfoViewModel, ActivityPersonalInfoBinding> implements View.OnClickListener {
    private static final int REQUEST_MY_CAR = 4;
    private String mMobile;
    private String mHeadImvUrl;
    private String mName;
    private String mIdentify;
    private String mCarNum;
    //选择头像
    private SelectPicPopupWindow selectPicPopupWindow;
    String TAG = "PersonalInfoActivity";
    private File picSaveDirectory; //图片存放的目录
    private File takePhotoFile;   //拍照得到的图片文件
    private File cropSmallFile;   //裁剪得到的图片文件

    public static final int MODIFY_NAME = 10;
    private static final int MODIFY_ID = 11;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mkDirForHeadPic();
        getLastIntent();
        initView();
        initLiveDataObersve();
    }
    /**
     * 为选择相册 or 拍照图片，创建保存目录
     */
    public void mkDirForHeadPic() {
        picSaveDirectory = new File(MyApplication.PIC_DIRECTORY);
        if (!picSaveDirectory.exists()) {
            picSaveDirectory.mkdirs();
        }
    }
    /**
     * 初始化控件显示
     */
    private void initView() {

        if(!TextUtils.isEmpty(mHeadImvUrl)){
            //显示用户头像
            Glide.with(this.getApplicationContext()).asBitmap().load(mHeadImvUrl)
                    .into(new BitmapImageViewTarget(mDataBinding.imvHeadPhoto) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getApplicationContext().getResources(), resource);
                            circularBitmapDrawable.setCircular(true);
                            mDataBinding.imvHeadPhoto.setImageDrawable(circularBitmapDrawable);
                        }
                    });
        }

        //显示真实姓名等基本信息
        if(!TextUtils.isEmpty(mName)) {
            mDataBinding.tvName.setText(mName);
        }
        if(!TextUtils.isEmpty(mIdentify)) {
            mDataBinding.tvIdentify.setText(mIdentify);
        }
        if(!TextUtils.isEmpty(mMobile)) {
            mDataBinding.tvMobile.setText(mMobile);
        }
        if(!TextUtils.isEmpty(mCarNum)) {
            mDataBinding.tvCarNum.setText(mCarNum);
        }
        mDataBinding.mobileLayout.setOnClickListener(this);
        mDataBinding.selectHeadPicLayout.setOnClickListener(this);
        mDataBinding.carManagerInfoLayout.setOnClickListener(this);
        mDataBinding.personNameLayout.setOnClickListener(this);
        mDataBinding.idCardLayout.setOnClickListener(this);
    }

    /**
     * 接口调用成功时，监听接口返回的数据
     */
    private void initLiveDataObersve() {

        //监听 “上传头像” 接口返回的数据，或者调用成功，失败等
        mViewModel.getPostFileLiveData().observe(this, new Observer<Result<JsonPostFileData>>() {
            @Override
            public void onChanged(Result<JsonPostFileData> result) {
                result.handler(new OnCallback<JsonPostFileData>() {
                    @Override
                    public void onSuccess(JsonPostFileData data) {
                        Toast.makeText(PersonalInfoActivity.this,R.string.upload_ok,Toast.LENGTH_SHORT).show();
                        String avatarThumbUrl = data.getThumbFileUrl();
                        String avatarUrl = data.getFileUrl();
                        MyLogCat.i(TAG,"fileUrl="+avatarUrl+",thumbUrl="+avatarThumbUrl);
                        CommonUtil.loadRoundPic(avatarUrl,mDataBinding.imvHeadPhoto,getApplicationContext());
                        mViewModel.updateUserInfo("","",avatarThumbUrl,avatarUrl,"");
                    }
                });
            }
        });

        //监听 “更新用户信息” 接口返回的数据，或者调用成功，失败等
        mViewModel.getUpdtUserLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        String modifyOk = PersonalInfoActivity.this.getResources().getString(R.string.modify_ok);
                        MyToast.showToastCenter(new WeakReference<Context>(PersonalInfoActivity.this),modifyOk,Toast.LENGTH_SHORT,true);
                    }
                });

            }
        });
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_personal_info;
    }
    /***
     * 获取上一页传递来的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle b = i.getExtras();
        if(b != null) {
            mHeadImvUrl = b.getString("headImvUrl");
            mName = b.getString("name");
            mIdentify = b.getString("identify");
            mMobile = b.getString("mobile");
            mCarNum = b.getString("carNum");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case MODIFY_NAME:
                    Bundle bName = data.getExtras();
                    if(bName != null) {
                        mName = bName.getString("name");
                        if(!TextUtils.isEmpty(mName)){
                            mDataBinding.tvName.setText(mName);
                        }
                    }
                    break;
                case MODIFY_ID:
                    Bundle bId = data.getExtras();
                    if(bId != null) {
                        mIdentify = bId.getString("identify");
                        if(!TextUtils.isEmpty(mIdentify)){
                            mDataBinding.tvIdentify.setText(mIdentify);
                        }
                    }
                    break;
                case REQUEST_MY_CAR: //去“车辆信息”页面，带回车牌号字段
                    Bundle b = data.getExtras();
                    if(b != null) {
                        mCarNum = b.getString("carNum");
                        if(!TextUtils.isEmpty(mCarNum)){
                            mDataBinding.tvCarNum.setText(mCarNum);
                        }
                    }
                    break;
                case MyConstant.REQUESTCODE_PICK:    //从系统相册返回后回调
                    if (data != null)
                        cropPhoto(data.getData());
                    break;
                case MyConstant.REQUESTCODE_CAMERA:  //从相机拍照返回后回调
                    if (Build.VERSION.SDK_INT >= 24) {
                        //拍照得到的图片文件takePhotoFile（picSaveDirectory/takePhoto.jpg），与之对应的contentUri
                        Uri contentUri = FileProvider.getUriForFile(PersonalInfoActivity.this, getPackageName(), takePhotoFile);
                        cropPhoto(contentUri);
                    } else {
                        cropPhoto(Uri.fromFile(takePhotoFile));
                    }
                    break;
                case MyConstant.REQUESTCODE_CUTTING://裁剪成功后回调
                    String cropSmallFilePath = cropSmallFile.getAbsolutePath();
                    //目前已裁剪，不需压缩已经很小了compressCropedPic(cropSmallFilePath);
                    MyLogCat.i(TAG,"cropSmallPath="+cropSmallFilePath);
                 /*   if(!TextUtils.isEmpty(cropSmallFilePath)){
                        CommonUtil.loadRoundPic(cropSmallFile,mDataBinding.imvHeadPhoto,getApplicationContext());
                    }*/
                    postAvatar(cropSmallFilePath);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传图片到服务器,分2步
     * step1.调用文件服务器的上传文件接口，上传图片文件到服务器，服务器生成并返回图片URL
     * step2.调用业务服务器的上传头像接口，上传图片URL与本次业务的标识如“头像”，，最终完成修改头像操作。
     */
    public void postAvatar(String filePath) {
        File file = null;
        if (!TextUtils.isEmpty(filePath)) {
            file = new File(filePath);
            MyLogCat.i(TAG,"fileNAme="+file.getName()+",abspath="+file.getAbsolutePath());
        }
        mViewModel.postImagFile(file,false);
    }


    /**
     * 裁剪图片
     * @param uri ：将要被裁剪的图片Uri路径
     */
    private void cropPhoto(Uri uri) {
        //裁剪成功的小图将放在picSaveDirectory目录下，路径为：picSaveDirectory/avatar.jpg
        cropSmallFile = new File(picSaveDirectory, "avatarSmall.jpg");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 400); //裁剪区域宽、高
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);  //不用返回数据到一个Bitmap对象，节省性能
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropSmallFile)); //裁剪成功的图片将输出到cropSmallFile路径下
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, MyConstant.REQUESTCODE_CUTTING);
    }

    /**
     * 再次压缩裁剪后的图片，并替换初步裁剪出来的图片
     * @param cropSamllPicPath
     * @return
     */
    public void compressCropedPic(String cropSamllPicPath) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(cropSamllPicPath);
        try {
            FileOutputStream cropedFileStream = new FileOutputStream(cropSmallFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, cropedFileStream);
            cropedFileStream.flush();
            cropedFileStream.close();
            //保存“裁剪并压缩后”的头像图片
            User user = User.getInstance(getApplicationContext());
            ContentValues userValues = new ContentValues();
            userValues.put("headPicPath", cropSamllPicPath);
            user.saveUserInfo(userValues);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 从相册选择照片，照相机拍照片
     */
    private View.OnClickListener selectPicitemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectPicPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.takePhotoBtn: //去拍照
                    goTakePhoto();
                    break;
                case R.id.pickPhotoBtn: //去相册
                    goAlbum();
                    break;
                default:
                    break;
            }
        }
    };

    private void goModifyPersonName(int fromPage) {
        Intent i = new Intent(PersonalInfoActivity.this, ModifyNamIdActivity.class);
        i.putExtra("fromPage",fromPage);
        if(fromPage == MODIFY_NAME){
            i.putExtra("name",mName);
            i.putExtra("title","修改姓名");
        }
        else if(fromPage == MODIFY_ID) {
            i.putExtra("idCard",mIdentify);
            i.putExtra("title","修改身份证");
        }
        startActivityForResult(i,fromPage);
    }

    /**
     * 去拍照
     */
    public void goTakePhoto() {
        //step1.先申请相关权限，相机与存储权限
        final String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        RxPermissions permissions = new RxPermissions(PersonalInfoActivity.this);
        permissions.setLogging(true);
        permissions.requestEachCombined(permissionRequest)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            MyLogCat.i(TAG,"同意了权限");
                            //step2.拍照片
                            takePhoto();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            //拒绝权限，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                            MyLogCat.i(TAG,"拒绝了权限");
                        } else {
                            //禁止权限，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                            MyLogCat.i(TAG,"禁止了权限");
                            RxjavaPermissionUtil.getInstance().alertOpenNavPermission(PersonalInfoActivity.this, permissionRequest);
                        }
                    }
                });
    }

    /**
     * 拍照片
     */
    private void takePhoto() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        //拍照获得的图片名为takePhoto.jpg，与之对应的文件对象为takePhotoFile，图片文件将保存在picSaveDirectory目录下
        takePhotoFile = new File(picSaveDirectory, "takePhoto.jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        /**
         *  在Android7.0以上,使用FileProvider获取Uri,即需要本APP授权，因为相机和本APP是两个应用，应用之间共享目录（或全路径）需要本APP授权给相机应用,
         *  然后，相机应用才能将拍照得到的照片，保存至contentUri路径下，实质就是takePhotoFile的存放路径picSaveDirectory/temp.jpg（本APP创建的文件目录）
         */
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(PersonalInfoActivity.this, getPackageName(), takePhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(takePhotoFile));
        }
        startActivityForResult(intent, MyConstant.REQUESTCODE_CAMERA);
    }

    /**
     * 去系统相册
     */
    public void goAlbum() {
        //step1.获取相关权限
        final String[] permissionPickRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        RxPermissions permissionsPick = new RxPermissions(PersonalInfoActivity.this);
        permissionsPick.setLogging(true);
        permissionsPick.requestEachCombined(permissionPickRequest)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {//同意后调用
                            choosePhoto();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            //拒绝，但没有选择  “以后不再询问”，以后申请权限，会继续弹出提示
                            MyLogCat.i(TAG, permission.name + "被拒绝");
                        } else {
                            //禁止，选择了“以后不再询问”，以后申请权限，将不会弹出提示
                            MyLogCat.i(TAG, permission.name + "被禁止");
                            RxjavaPermissionUtil.getInstance().alertOpenNavPermission(PersonalInfoActivity.this, permissionPickRequest);
                        }
                    }
                });
    }

    /**
     * 从系统相册里选择
     */
    private void choosePhoto() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, MyConstant.REQUESTCODE_PICK);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.mobileLayout:
                Intent i = new Intent(PersonalInfoActivity.this, ModifyMobileActivity.class);
                i.putExtra("mobile",mMobile);
                startActivity(i);
                break;
            case R.id.carManagerInfoLayout:
                Intent intent = new Intent(PersonalInfoActivity.this, CarInfoManageActivity.class);
                startActivityForResult(intent,REQUEST_MY_CAR);
                break;
            case R.id.selectHeadPicLayout:
                selectPicPopupWindow = new SelectPicPopupWindow(this, selectPicitemsOnClick,false);
                selectPicPopupWindow.showAtLocation(findViewById(R.id.mainLayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.personNameLayout:
                goModifyPersonName(MODIFY_NAME);
                break;
            case R.id.idCardLayout:
                goModifyPersonName(MODIFY_ID);
                break;
        }
    }




}